//
//  PaperCardViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/16.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import SnapKit
import Then

class PaperCardViewController: ViewController, LeftBarButtonItemable {
    var submitBtn: UIButton!
    var collectionView: UICollectionView!
    
    var vm: PaperReportViewModel!
    var datasource: RxCollectionViewSectionedReloadDataSource<PaperReportSection>!
    var selectHandle:((PaperItemModel)->Void)?
    var submitHandle: VoidBlock?
    init(_ paper: PaperModel) {
        self.vm = PaperReportViewModel.init(paper)
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        initUI()
        bindUI()
    }
 
 
    private func initUI() {
    
        title = "题卡"
        
        setLeftItem()
        
        let flowLayout = LSFEqualCellSpaceFlowLayout.init().then { (layout) in
            layout.alignType = .left
            layout.minimumLineSpacing = 20
            layout.cellSpacing = 20
            layout.itemSize = CGSize.init(width: 30, height: 30)
            layout.sectionInset = UIEdgeInsets.init(top: 0, left: 15, bottom: 20, right: 15)
            layout.headerReferenceSize = CGSize.init(width: k_screen_width, height: 39)
            layout.footerReferenceSize = CGSize.init(width: k_screen_width, height: 11)
        }
        
        collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: flowLayout).then({ (cv) in
            cv.backgroundColor = UIColor.white
            cv.register(PaperReportCell.classForCoder(), forCellWithReuseIdentifier: "PaperReportCell")
            cv.register(PaperReportHeaderView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "PaperReportHeaderView")
            cv.register(PaperReportFooterView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "PaperReportFooterView")
            
            view.addSubview(cv)
            
        })
        
        //考试模式，显示交卷按钮
        if vm.paper.method == .exam {
            
            collectionView.snp.makeConstraints({ (maker) in
                maker.top.leading.trailing.equalToSuperview()
            })
            
            let bottomView = UIView().then({ (view) in
                view.backgroundColor = UIColor.white
                
                self.view.addSubview(view)
                view.snp.makeConstraints({ (maker) in
                    maker.leading.trailing.equalToSuperview()
                    maker.bottom.equalTo(0 - safeAreaInsets().bottom)
                    maker.top.equalTo(collectionView.snp.bottom)
                    maker.height.equalTo(56)
                })
            })
            
            submitBtn = UIButton.init(type: .custom).then({ (btn) in
                btn.setTitle("交卷", for: .normal)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
                btn.setTitleColor(Config.default.themeColor, for: .normal)
                btn.layer.borderColor = Config.default.themeColor.cgColor
                btn.layer.borderWidth = 1.0
                btn.layer.cornerRadius = 18
                btn.clipsToBounds = true
                
                bottomView.addSubview(btn)
                btn.snp.makeConstraints({ (maker) in
                    maker.size.equalTo(CGSize.init(width: 255, height: 36))
                    maker.centerY.equalToSuperview()
                    maker.centerX.equalToSuperview()
                })
            })
        }
            
            //练习模式，不显示交卷按钮
        else {
            
            collectionView.snp.makeConstraints({ (maker) in
                maker.edges.equalTo(safeAreaInsets())
//                maker.top.leading.trailing.equalToSuperview()
            })
        }
       
    }
    
    private func bindUI() {
        
        // Cell
        datasource = RxCollectionViewSectionedReloadDataSource.init(configureCell: { (ds, cv, ip, item) -> UICollectionViewCell in
            let cell = cv.dequeueReusableCell(withReuseIdentifier: "PaperReportCell", for: ip) as! PaperReportCell
            cell.set(item.index, userAnswer: item.userAnswer)
            return cell
        }, configureSupplementaryView: { [weak self] (ds, cv, kind, ip) -> UICollectionReusableView in
            
            if kind == UICollectionElementKindSectionHeader {
                let headerView = cv.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "PaperReportHeaderView", for: ip) as! PaperReportHeaderView
                if let sections = self?.vm.vmDatas.value {
                    if sections.count > ip.section {
                        let section = sections[ip.section]
                        headerView.set(section.header)
                    }
                }
                return headerView
            }
            else {
                let view = cv.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "PaperReportFooterView", for: ip) as! PaperReportFooterView
                
                return view
            }
        })
        
        
        collectionView.rx.modelSelected(PaperItemModel.self).subscribe(onNext: { [weak self] (item) in
            self?.selectHandle?(item)
            self?.navigationController?.popViewController(animated: true)
        }).disposed(by: disposeBag)
        
        vm.vmDatas.asObservable().bind(to: collectionView.rx.items(dataSource: datasource)).disposed(by: disposeBag)
        vm.transform()
        
        
        if submitBtn != nil {
            submitBtn.rx.tap.bind{ [weak self] in
                self?.submitHandle?()
                }.disposed(by: disposeBag)
        }
    }
}

